import { login, logout, getUserInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";

const user = {

    state: {
        userId: '',
        account: '',
        realName: '',
        avatar: '',
        token: getToken(),
        roles: []
    },
    mutations: {
        SET_USER_ID: (state, userId) => {
            state.userId = userId
        },
        SET_ACCOUNT: (state, account) => {
            state.account = account
        },
        SET_REAL_NAME: (state, realName) => {
            state.realName = realName
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        }
    },
    actions: {
        // 账号登录（支持用户名，手机号，邮箱）
        Login({ commit, state }, userInfo) {
            const account = userInfo.account.trim()

            return new Promise((resolve, reject) => {
                login(account, userInfo.password).then(response => {
                    const data = response.data.data

                    if(data != undefined) {
                        commit('SET_USER_ID', data.id)
                        commit('SET_ACCOUNT', data.account)
                        commit('SET_REAL_NAME', data.realName)
                        commit('SET_AVATAR', data.avatar)
                        commit('SET_TOKEN', data.token)
                    }


                    resolve(response)
                }).catch(() => {
                    reject({status: false, msg: '登录异常，请联系管理员'})
                })
            })
        },

        //获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo(state.userId).then((res) => {
                    //console.log(res.data)
                }).catch(() => {

                })
            });
        },

        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {

                logout(state.token).then(() => {
                    commit('SET_USER_ID', '')
                    commit('SET_ACCOUNT', '')
                    commit('SET_REAL_NAME', '')
                    commit('SET_AVATAR', '')
                    commit('SET_TOKEN', '');

                    commit('CLEAR_VISITED_VIEWS')

                    removeToken()
                    resolve()
                }).catch(() => {
                    reject()
                })
            })
        },

        // 前端 登出
        FedLogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }

}

export default user
